package com.xhwl.data.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.data.config.GlobalExceptionHandler;
import com.xhwl.data.service.IOrganizationService;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CodeGenerator {


    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int MIN_LENGTH = 6;
    private static final int MAX_LENGTH = 10;


    public String generateUniqueCode(Integer enterprise,IOrganizationService organizationService) {
        String code;
        int count = 0;
        do {
            code = generateRandomCode();
            QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("enterprise_id",enterprise);
            queryWrapper.eq("is_deleted",0);
            queryWrapper.eq("code",code);
            List<Organization> list = organizationService.list(queryWrapper);
            if (list.isEmpty()){
                return code;
            }
            count++;
            if (count == 1000){
                throw new DataException("组织编码生成失败");
            }
        } while (true);
    }



    private String generateRandomCode() {
        int length = new Random().nextInt(MAX_LENGTH - MIN_LENGTH + 1) + MIN_LENGTH;
        StringBuilder codeBuilder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int randomIndex = new Random().nextInt(CHARACTERS.length());
            codeBuilder.append(CHARACTERS.charAt(randomIndex));
        }
        return codeBuilder.toString();
    }

}

